import axios from 'axios'
import store from '@/store'
import storage from 'store'
import notification from 'ant-design-vue/es/notification'
import { ACCESS_TOKEN } from '@/store/mutation-types'

const addErrorLog = errorInfo => {
  const { statusText, status, request: { responseURL } } = errorInfo
  const info = {
    type: 'ajax',
    code: status,
    mes: statusText,
    url: responseURL
  }
  store.dispatch('addErrorLog', info)
}
// 创建 axios 实例
const request = axios.create({
  // API 请求的默认前缀
  baseURL: window.service.baseURL,
  timeout: 180000 // 请求超时时间
})

// 异常拦截处理器
const errorHandler = (error) => {
  if (error.response) {
    const data = error.response.data
    const { config } = JSON.parse(JSON.stringify(error))
    const errorInfo = {
      statusText: error.request.statusText,
      status: error.request.status,
      request: { responseURL: config.url }
    }
    addErrorLog(errorInfo)
    // 从 localstorage 获取 token
    const token = storage.get(ACCESS_TOKEN)
    if (error.response.status === 403) {
      notification.error({
        message: '禁止访问',
        description: data.message
      })
    }
    if (error.response.status === 401) {
      notification.error({
        message: '未登录',
        description: '登录验证失败'
      })
      if (token) {
        store.dispatch('Logout').then(() => {
          setTimeout(() => {
            window.location.reload()
          }, 1500)
        })
      }
    }
  }
  return Promise.reject(error)
}

// request interceptor
request.interceptors.request.use(config => {
  const token = storage.get(ACCESS_TOKEN)
  // 如果 token 存在
  // 让每个请求携带自定义 token 请根据实际情况自行修改
  if (token) {
    config.headers['Authorization'] = token
  }
  return config
}, errorHandler)

// response interceptor
request.interceptors.response.use((response) => {
  if (response.data.code !== 200 && response.data.code !== 0) {
    const { config } = JSON.parse(JSON.stringify(response))
    const errorInfo = {
      statusText: response.data.trace,
      status: response.data.code,
      request: { responseURL: config.url }
    }
    addErrorLog(errorInfo)
    return Promise.reject(response.data)
  } else {
    return response.data
  }
}, errorHandler)

export default request
